import { reqLogout, reqUserLogin } from "@/api";

const state = {
    userInfo:{
        name:localStorage.getItem('userName'),
        token:localStorage.getItem('token')
    }
}

const actions = {
    // 登录
    async userLogin({commit},obj){
        const res = await reqUserLogin(obj)
        if(res.code === 200){
            commit('SAVE_USER_INFO',res.data)
            // 存储到本地一份
            localStorage.setItem('userName',res.data.name)
            localStorage.getItem('token',res.data.token)
        }else{
            console.log(res.message);
        }
    },

    // 登出
    async userLogout({commit}){
        const res = await reqLogout();
        if(res.code === 200){
            // 清空本地存储
            localStorage.removeItem('userName')
            localStorage.removeItem('token')

            commit('REMOVE_USER_INFO')
        }else{
            console.log(res.message);
        }
    } 
}

const mutations = {
    SAVE_USER_INFO(state,payload){
        state.userInfo = payload
    },

    REMOVE_USER_INFO(state){
        state.userInfo.name = ''
        state.userInfo.token = ''
    }
}

const getters = {}

export default {
    namespaced:true,
    state,
    actions,
    mutations,
    getters
}